<?php

namespace Laoha\Nav;

use Illuminate\Support\Facades\Schema;
use Laoha\Config\LaohaConfig;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use Illuminate\Routing\Controller;

class ConfigController extends Controller
{
    use HasResourceActions;
	protected $root=0;
    /**
     * Index interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function index(Content $content)
    {
        $root = request('root',0);
		if($root){		
			$navModel = new LaohaNav();
			$nav = $navModel::where('id',$root)->orWhere('name',$root)->first();
			
			if(!$nav){
				throw new \Exception('未找到指定导航');
				//throw new \Exception(trans('laoha.nofindnav'));
			}else{
				$this->root = $nav->id;
			}
			
			return $content
				->title($nav->name.' 导航管理')
				->description($nav->title)
				->breadcrumb(
						['text' => '导航列表', 'url' => 'laoha/nav'],
						['text' => '导航管理']
					)
				->row(function (Row $row) {
					$row->column(6, $this->treeView()->render());

					$row->column(6, function (Column $column) {

						$form = new \Encore\Admin\Widgets\Form();
						$form->action(admin_base_path('laoha/nav').'?root='.$this->root);

						$navModel = new LaohaNav($this->root);

						$form->select('parent_id', trans('admin.parent_id'))->options($navModel::selectOptions());
						$form->text('title', trans('admin.title'))->rules('required');
						$form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp());
						$form->text('url', '链接');
						$form->hidden('root')->default($this->root);
						$form->hidden('_token')->default(csrf_token());

						$column->append((new Box(trans('admin.new'), $form))->style('success'));
					});
				});
		}else{
			return $content
				->title('导航列表')
				->description('可使用 nav(name) 方式引入导航')
				->body($this->grid());
		}
    }

    protected function grid()
    {  
        $navModel = new LaohaNav();
		$grid = new Grid($navModel);
		$grid->model()->where('root', 0);
		$grid->filter(function($filter){
			// 去掉默认的id过滤器
			$filter->disableIdFilter();
			// 在这里添加字段过滤器
			$filter->like('name', 'name');

		});
		$grid->disableRowSelector();
		$grid->disableColumnSelector();
		
        $grid->column('name', trans('admin.name'));
		$grid->column('title', trans('admin.title'));
		$grid->column('id', '管理')->display(function ($id) {
			return "<a href='".route('admin.laoha.nav.index', ['root' => $id])."' style='color:blue'>导航管理</a>";
		});

		$grid->actions(function (Grid\Displayers\Actions $actions) {
			$actions->disableView();
		});
 
        return $grid;
    }
    /**
     * Create interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('创建导航')
            ->description(trans('admin.create'))
            ->body($this->navform());
    }

    /**
     * Redirect to edit page.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function show($id)
    {
        //return redirect()->route('admin.laoha.nav.edit', ['id' => $id]);
    }

    /**
     * @return \Encore\Admin\Tree
     */
    protected function treeView()
    {
        $navModel = new LaohaNav($this->root);

        return $navModel::tree(function (Tree $tree) {
            $tree->disableCreate();

            $tree->branch(function ($branch) {
                $payload = "<i class='fa {$branch['icon']}'></i>&nbsp;<strong>{$branch['title']}</strong>";

                if (!empty($branch['url'])) {
                    $payload .= "&nbsp;&nbsp;&nbsp;<a href=\"{$branch['url']}\" class=\"dd-nodrag\">{$branch['url']}</a>";
                }

                return $payload;
            });
        });
    }

    /**
     * Edit interface.
     *
     * @param string  $id
     * @param Content $content
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {
		$nav = LaohaNav::find($id);
		$this->root = $nav->root;
		if($this->root){
			return $content
            ->title($nav->name.' 导航')
            ->description(trans('admin.edit'))
            ->row($this->itemform()->edit($id));
		}else{
			return $content
            ->title('导航')
            ->description(trans('admin.edit'))
            ->row($this->navform()->edit($id));
		}

    }

    /**
     * Make a nav form builder.
     *
     * @return Form
     */
    protected function navform()
    {
        $navModel = new LaohaNav(0);
        $form = new Form($navModel);
        $form->display('id', 'ID');
		$form->text('name', trans('admin.name'))->rules('required')
			->help('名称必须是英文开头且只包含字母、数字、下划线');
        $form->text('title', trans('admin.title'))->rules('required');
        return $form;
    }

    protected function itemform()
    {
        $navModel = new LaohaNav($this->root);
        $form = new Form($navModel);
        $form->display('id', 'ID');
        $form->select('parent_id', trans('admin.parent_id'))->options($navModel::selectOptions());
        $form->text('title', trans('admin.title'))->rules('required');
        $form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp());
        $form->text('url', '链接'); 
		$form->hidden('root')->default($this->root);
        return $form;
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $navModel = new LaohaNav($this->root);

        $form = new Form($navModel);
        $form->display('id', 'ID');
        $form->select('parent_id', trans('admin.parent_id'))->options($navModel::selectOptions());
		$form->text('name', trans('admin.name'))		
			->creationRules('required|unique:laoha_navs,name|regex:/^[A-Za-z][A-Za-z0-9_]+$/',['regex' => '名称必须是英文开头且只包含字母、数字、下划线',])
			->updateRules('required|unique:laoha_navs,name,{{id}}|regex:/^[A-Za-z][A-Za-z0-9_]+$/',['regex' => '名称必须是英文开头且只包含字母、数字、下划线',]);
        $form->text('title', trans('admin.title'))->rules('required');
        $form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp());
        $form->text('url', '链接'); 
		$form->hidden('root')->default($this->root);
        return $form;
    }

 
    /**
     * Help message for icon field.
     *
     * @return string
     */
    protected function iconHelp()
    {
        return 'For more icons please see <a href="http://fontawesome.io/icons/" target="_blank">http://fontawesome.io/icons/</a>';
    }

    public function destroy($id)
    {
        $navModel = new LaohaNav();
		$nav = $navModel->where('root',$id)->first();
		if($nav){
            $response = [
                'status'  => false,
                'message' => '请先删除此导航下的所有导航子项目',
            ];
			return response()->json($response);
		}
		return $this->form()->destroy($id);
    }
}
